import RedisUtils from '../../utils/RedisUtils'
import {nedb} from '../../api/redis/redisDatabase'

export const commandMonitor = (doc, db, callback) => {
  RedisUtils.getRedisConnect(doc, db, (client) => {
    console.log(client)
    // eslint-disable-next-line handle-callback-err
    return client.monitor((err, monitor) => {
      monitor.on('monitor', function (time, args, source, database) {
        let doc = {
          database: 'redis',
          table: 'monitor',
          host: client.options.host,
          datetime: time.split('.')[0],
          args: args,
          source: source,
          data: database
        }
        // eslint-disable-next-line handle-callback-err
        nedb.insert(doc, (err, newDoc) => {
          callback(newDoc)
        })
      })
    })
  })
}

export const commandMonitorCluster = (doc, db, callback) => {
  // eslint-disable-next-line handle-callback-err
  nedb.find({pId: doc.pId}, (err, docs) => {
    for (const newDoc of docs) {
      RedisUtils.getRedisConnect(newDoc, db, (client) => {
        console.log(client)
        // eslint-disable-next-line handle-callback-err
        client.monitor((err, monitor) => {
          monitor.on('monitor', function (time, args, source, database) {
            let doc = {
              database: 'redis',
              table: 'monitor',
              host: client.options.host + ':' + client.options.port,
              datetime: time.split('.')[0],
              args: args,
              source: source,
              data: database
            }
            // eslint-disable-next-line handle-callback-err
            nedb.insert(doc, (err, newDoc) => {
              callback(newDoc)
            })
          })
        })
      })
    }
  })
}

export const countCommandCluster = (doc, time, callback) => {
  let data = {}
  RedisUtils.getRedisConnect(doc, 0, (client) => {
    // eslint-disable-next-line handle-callback-err
    client.cluster('nodes', (err, result) => {
      let split = result.split('\n')
      // eslint-disable-next-line no-unused-expressions
      async () => {
        for (const sp of split) {
          let split1 = sp.split(' ')
          // eslint-disable-next-line handle-callback-err
          const data = await nedb.find({host: split1[1], datetime: time}, (err, docs) => {
            data[split1[1]] = docs.length
          })
        }
        callback(data)
      }
    })
  })
}

export const listCommandMonitor = (host, time, callback) => {
  // eslint-disable-next-line handle-callback-err
  return nedb.find({host: host, datetime: time}, (err, docs) => {
    callback(docs.length)
  })
}

export const getKeys = (doc, db, callback) => {
  RedisUtils.getRedisConnect(doc, db, (client) => {
    // eslint-disable-next-line handle-callback-err
    let stream = client.scanStream({
      count: 30
    })
    stream.on('end', function () {
    })
    return stream.on('data', function (resultKeys) {
      callback(resultKeys)
    })
  })
}
